package com.chenailin.www.controller.user;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

import com.chenailin.www.model.dto.UserDTO;
import com.chenailin.www.service.UserService;
import com.chenailin.www.serviceimpl.UserServiceImpl;
import com.google.gson.Gson;

/**
 * @author evi
 */
@WebServlet("/saveUserInfo")
public class SaveController extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();

        // 检查用户是否已登录
        HttpSession session = req.getSession(false);
        if (session == null || session.getAttribute("currentUser") == null) {
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            String json = "{\"code\": 401, \"message\": \"用户未登录或会话已过期\"}";
            out.print(json);
            return;
        }

        // 读取请求体
        StringBuilder requestBody = new StringBuilder();
        BufferedReader reader = req.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            requestBody.append(line);
        }

        // 解析 JSON 数据
        Gson gson = new Gson();
        UserDTO userDTO = gson.fromJson(requestBody.toString(), UserDTO.class);

        // 这里可以添加保存用户信息到数据库的逻辑
        // 示例：假设已经有一个 UserService 类用于处理用户信息保存
        UserService userService = new UserServiceImpl();
//        boolean isSaved = userService.saveUserInfo(userDTO);
        boolean isSaved = false;
        if (isSaved) {
            String json = "{\"code\": 200, \"message\": \"保存成功\"}";
            out.print(json);
        } else {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            String json = "{\"code\": 500, \"message\": \"保存失败，请稍后重试\"}";
            out.print(json);
        }
        out.flush();
    }
}

